#!/usr/bin/env python3
"""
修复权限表中的NULL值
解决 is_system 字段为 NULL 导致的 Pydantic 验证错误
"""

import asyncio
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import text
from app.core.database import AsyncSessionLocal
from app.core.logger import logger


async def fix_permission_null_values():
    """修复权限表中的NULL值"""
    try:
        async with AsyncSessionLocal() as db:
            logger.info("开始修复权限表中的NULL值...")
            
            # 修复 is_system 字段的 NULL 值
            result = await db.execute(text("""
                UPDATE dp_permissions 
                SET is_system = FALSE 
                WHERE is_system IS NULL
            """))
            
            updated_count = result.rowcount
            logger.info(f"修复了 {updated_count} 个权限记录的 is_system 字段")
            
            # 检查是否还有其他 NULL 值
            result = await db.execute(text("""
                SELECT COUNT(*) as count
                FROM dp_permissions 
                WHERE is_system IS NULL
            """))
            
            remaining_null = result.scalar()
            if remaining_null == 0:
                logger.info("✅ 所有权限记录的 is_system 字段都已修复")
            else:
                logger.warning(f"⚠️ 仍有 {remaining_null} 个权限记录的 is_system 字段为 NULL")
            
            # 提交更改
            await db.commit()
            logger.info("数据库更改已提交")
            
            return True
            
    except Exception as e:
        logger.error(f"修复权限表失败: {str(e)}")
        return False


async def verify_fix():
    """验证修复结果"""
    try:
        async with AsyncSessionLocal() as db:
            # 检查权限表的数据完整性
            result = await db.execute(text("""
                SELECT 
                    COUNT(*) as total_permissions,
                    SUM(CASE WHEN is_system IS NULL THEN 1 ELSE 0 END) as null_is_system,
                    SUM(CASE WHEN is_system = TRUE THEN 1 ELSE 0 END) as system_permissions,
                    SUM(CASE WHEN is_system = FALSE THEN 1 ELSE 0 END) as user_permissions
                FROM dp_permissions
            """))
            
            row = result.fetchone()
            
            logger.info("权限表数据统计:")
            logger.info(f"  总权限数: {row.total_permissions}")
            logger.info(f"  NULL is_system: {row.null_is_system}")
            logger.info(f"  系统权限: {row.system_permissions}")
            logger.info(f"  用户权限: {row.user_permissions}")
            
            return row.null_is_system == 0
            
    except Exception as e:
        logger.error(f"验证修复结果失败: {str(e)}")
        return False


async def main():
    """主函数"""
    try:
        logger.info("🔧 DataPlexus 权限表修复工具")
        logger.info("=" * 50)
        
        # 修复 NULL 值
        success = await fix_permission_null_values()
        if not success:
            logger.error("❌ 修复失败")
            sys.exit(1)
        
        # 验证修复结果
        verified = await verify_fix()
        if not verified:
            logger.error("❌ 验证失败")
            sys.exit(1)
        
        logger.info("=" * 50)
        logger.info("🎉 权限表修复完成！")
        
    except Exception as e:
        logger.error(f"❌ 修复过程失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
